//
//  LHOAuthViewController.swift
//  LH-Swift-WeiBo
//
//  Created by liuhao on 16/9/25.
//  Copyright © 2016年 liuhao. All rights reserved.
//


/*
 
 
 App Key：3040654236
 App Secret：73234625eaae086265f56d915596752f
 创建时间：2016-09-25
 */

import UIKit
import SVProgressHUD
class LHOAuthViewController: UIViewController {

    
    
    lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.isOpaque = false
        
        view = webView
        
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        
        webView.delegate = self
        
        //设置nav的button
        
        setNavButton()
        
        //调用函数设置页面
        loadOAuthView()
        
    }
    
    
    private func setNavButton() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
        
        //上线的时候一定要注意将方法 注销掉
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(fillAccount))
    }
    
    
    @objc private func fillAccount() {
        //webView执行js
        
        //webView执行js
//        let jsString = "document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'onoyomg' "
        let jsString = "document.getElementById('userId').value = '857035991@qq.com', document.getElementById('passwd').value = 'liu5780840liu' "
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    @objc private func close() {
    
        //取消模态
        dismiss(animated:true, completion: nil)
    
    }
    
    
    
    private func loadOAuthView() {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        //加载页面
        webView.loadRequest(req)
    
    }

}


//代理方法
//用延展来拓展方法
//swift中 推荐协议方法在扩展中实现 extension
//这个扩展就是用来专门实现 代理方法的
extension LHOAuthViewController: UIWebViewDelegate {
    //实现协议方法
    func webViewDidStartLoad(_ webView: UIWebView) {
      
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
       
        SVProgressHUD.dismiss()
    }
    
   //MARK: 这个方法调用两次,一次失败,一次成功,我快疯了

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //截取重定向url中的code
        //绝对路径 url对象的 Sting 形式

        let urlStirng = request.url?.absoluteString ?? ""

        //如果urlStirng 中包含了 重定向地址 就认为授权成功 就可以开始 截取code
        let flag = "code="
        if urlStirng.contains(flag) {
    
            //获取url的参数部分
            let query = request.url?.query ?? ""

            let code = (query as NSString).substring(from: flag.characters.count)

         //请求数据
            LHUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code: code, finished: { (success) in
                
                //如果失败
                if !success {
                    SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                    return
                }
                //如果成功
                print("登录获取用信息成功")
                
                //MARK:获取用户的信息然后显示欢迎界面
                NotificationCenter.default.post(name: NSNotification.Name(KchangeRootViewController), object: "welcome")
                
                
            })
            return false
        }
        return true
    }

}
